home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6988 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: jaxnet.jaxnet.com!jax!garyg
  2. From: garyg@jax.jaxnet.com (Gary M. Greenberg)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Arrays of strings
  5. Date: 17 Feb 1996 00:04:21 GMT
  6. Organization: Southeast Network Services, Inc.
  7. Message-ID: <4g3625$f0m@jaxnet.jaxnet.com>
  8. NNTP-Posting-Host: jax.jaxnet.com
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. Larry DiGiovanni (ldigiova@nova.umuc.edu) wrote:
  12.  
  13. : I'm trying to read lines of a text file and load those lines into an 
  14. : array.  I have a couple of questions...
  15.  
  16. Note: Someone will no doubt correct any incorrect terminology.
  17.  
  18. : 1.  How do I declare the array to contain the text.  When it is declared, 
  19. : I will not know how many lines are in the text file.  char **txtarray?
  20.  
  21. Yes, that can work. "char **txtarray;" now is an uninitialized pointer
  22. of pointers to character arrays <I hope I stated that correctly>.
  23.  
  24. : 2.  How do I allocate the space for the data once I know how many lines 
  25. : are in the text file?  txtarray = malloc((size_t)(nelements))?
  26.  
  27. Make sure to #include <stdlib.h> for malloc, and then do something like:
  28.     /* assuming each line is one of your character arrays, read the file
  29.        and count the number of lines. Then you can ... */
  30.     txtarray=malloc(X * (char **)); /* X == number of char arrays */
  31.     /* do the error checking ... */
  32.  
  33. Note that this only allocates space for **txtarray; nothing is allocated for
  34. each of the individual character arrays yet.
  35.  
  36. : 3.  What is the best way to read from the text file into the array 
  37. : elements? fscanf? fgets?
  38.  
  39. I use fgets, and process it accordingly, stripping off the newline, and then
  40. assign each line <character array, using assumptions above> to one element
  41. of **txtarray. you must malloc each character array and error check 
  42. accordingly.
  43.  
  44. : I have had no success reading directly into the 
  45. : elements with these two functions.  I don't understand why, but it may be 
  46. : related to my poor understanding of (1) and (2) above as well.
  47.  
  48. Post some of the not-working attempt. It is the best way to learn, honest.
  49.  
  50. : Any help would be greatly appreciated.  TIA
  51.  
  52. : Larry DiGiovanni
  53.  
  54. another C neophyte,
  55.  
  56. gary    /* the Sorcerer's Apprentice */
  57.  
  58. "Why do we have to hide from the police, Daddy?"
  59. "Because we use vi, honey. They use emacs."
  60. "Unless we're on the Mac. Then we use BBEdit 'cause 'It doesn't suck.'"
  61.